package com.sunshine.wrongquestionset.activity.add_question

import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.text.Html
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import androidx.core.view.get
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.button.MaterialButton

import com.google.android.material.chip.Chip
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.dialog.MaterialDialogs
import com.google.android.material.imageview.ShapeableImageView
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.textfield.TextInputEditText

import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.base.BaseActivity
import com.sunshine.wrongquestionset.callback.OnRefreshListener
import com.sunshine.wrongquestionset.room.entity.QuestionEntity
import com.sunshine.wrongquestionset.room.entity.QuestionSetActivityBean
import com.sunshine.wrongquestionset.room.entity.QuestionSetEntity
import com.sunshine.wrongquestionset.room.entity.SubjectEntity
import com.sunshine.wrongquestionset.utils.TagUtils
import com.sunshine.wrongquestionset.utils.TimeUtils
import es.dmoral.toasty.Toasty

import kotlinx.android.synthetic.main.activity_add_question.*
import kotlinx.android.synthetic.main.activity_add_question.imageView_expend
import kotlinx.android.synthetic.main.activity_my_subject.*
import kotlinx.android.synthetic.main.activity_question_set.*
import kotlinx.android.synthetic.main.item_search.*
import java.lang.StringBuilder
import java.util.*
import kotlin.collections.ArrayList

class AddQuestionActivity : BaseActivity() {

    private lateinit var viewModel: AddQuestionViewModel
    //要添加的题目类型
    private var questionType = QUESTION_TYPE_XZ
    //错题集，默认1
    private var questionSetId = 1
    //科目，默认1
    private var subjectId = 1

    private var answerEditText: TextInputEditText? = null

    //当前的模式是添加还是编辑
    private var type = TYPE_ADD


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_question)

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(AddQuestionViewModel::class.java)

        type = intent?.getIntExtra("type", TYPE_ADD)?: TYPE_ADD

        subjectId = intent?.getIntExtra("subjectId", 1)?:1
        questionSetId = intent?.getIntExtra("setId", -1)?:-1

        when (type) {
            TYPE_ADD -> {
                setTitle(getString(R.string.label_add_question))
                updateQuestionTypeView()
            }
            TYPE_EDIT -> {
                setTitle(getString(R.string.label_edit_question))
                initEditContent()
            }
        }

        initQuestionSubjectSpinner()
        initQuestionTypeSpinner()
        initAddQuestionTitle()

        initQuestionTag()

        fab_to_save_question.setOnClickListener {
            if (questionSetId == -1) {
                Snackbar.make(add_question_root, getString(R.string.question_set_empty), Snackbar.LENGTH_SHORT).show()
            } else {
                val userId = getLoginUserId()
                val titleText = edit_add_title.text?.toString()?:""
                val answerText = answerEditText?.text?.toString()?:""
                val scoreText = edit_score.text?.toString()?:""
                //用户信息为空，可能是重新加载过activity
                if (userId.isBlank()) {
                    Snackbar.make(add_question_root, getString(R.string.get_user_config_error), Snackbar.LENGTH_SHORT).show()
                }
                //内容为空的情况
                else if (titleText.isBlank() || answerText.isBlank()) {
                    Snackbar.make(add_question_root, getString(R.string.tilte_or_answer_empty), Snackbar.LENGTH_SHORT).show()
                }
                else if (scoreText.isBlank()) {
                    Snackbar.make(add_question_root, getString(R.string.score_empty), Snackbar.LENGTH_SHORT).show()
                }
                else {
                    //获取标签信息
                    val tag = StringBuilder()
                    for (i in 0 until chip_group.childCount) {
                        tag.append((chip_group[i] as Chip).text).append("#")
                    }

                    //题目难度
                    val difficulty = ratingBar.rating

                    if (type == TYPE_ADD) {
                        try {
                            //选择熟悉程度，因为熟悉程度对题目影响较大，所以放到这里
                            val builder = MaterialAlertDialogBuilder(this)
                            val dialog = builder.create()
                            dialog.apply {
                                val view: View = LayoutInflater.from(this@AddQuestionActivity).inflate(R.layout.view_choose_familiarity, null, false)
                                val max: ImageView = view.findViewById(R.id.shapeableImageView_max)
                                val mid: ImageView = view.findViewById(R.id.shapeableImageView_mid)
                                val min: ImageView = view.findViewById(R.id.shapeableImageView_min)

                                max.setOnClickListener {
                                    dialog.dismiss()
                                    toSave(
                                        userId,
                                        if (tag.isNotEmpty()) tag.substring(0, tag.length - 1).toString() else "",
                                        titleText,
                                        answerText,
                                        QuestionEntity.FAMILIARITY_MAX,
                                        scoreText.toFloat(),
                                        difficulty
                                    )
                                }
                                mid.setOnClickListener {
                                    dialog.dismiss()
                                    toSave(
                                        userId,
                                        if (tag.isNotEmpty()) tag.substring(0, tag.length - 1).toString() else "",
                                        titleText,
                                        answerText,
                                        (QuestionEntity.FAMILIARITY_MAX + QuestionEntity.FAMILIARITY_MIN) / 2,
                                        scoreText.toFloat(),
                                        difficulty
                                    )
                                }
                                min.setOnClickListener {
                                    dialog.dismiss()
                                    toSave(
                                        userId,
                                        if (tag.isNotEmpty()) tag.substring(0, tag.length - 1).toString() else "",
                                        titleText,
                                        answerText,
                                        QuestionEntity.FAMILIARITY_MIN,
                                        scoreText.toFloat(),
                                        difficulty
                                    )
                                }
                                setTitle(getString(R.string.choose_familiarity))
                                setView(view)
                            }

                            dialog.show()

                        }catch (e: Exception) {
                            Snackbar.make(add_question_root, "出错了 $e", Snackbar.LENGTH_SHORT).show()
                        }
                    }

                    //编辑模式不用选择熟悉程度
                    else {
                        toSave(
                            userId,
                            if (tag.isNotEmpty()) tag.substring(0, tag.length - 1).toString() else "",
                            titleText,
                            answerText,
                            -1.0f,
                            scoreText.toFloat(),
                            difficulty
                        )
                    }
                }
            }
        }
    }

    /**
     * 初始化题目科目的下拉选择
     */
    private fun initQuestionSubjectSpinner() {
        viewModel.getQuestionSubject(getLoginUserId()).observe(this, Observer {
            val spinnerText: TextView = include_question_subject.findViewById(R.id.textView_spinner)
            val spinner: Spinner = include_question_subject.findViewById(R.id.spinner)

            spinnerText.text = getString(R.string.question_subject)
            spinner.adapter = SpinnerAdapter(
                this,
                R.layout.view_spinner_item,
                R.id.textView_spinner_item,
                it?.toMutableList()?:ArrayList<SubjectEntity>().toMutableList(),
                SpinnerAdapter.TYPE_SUBJECT
            )

            //设置默认选择的科目，因为上次或者首次进入，用户可能有希望的选择
            if (it != null) {
                for (i in it.indices) {
                    if (it[i].id == subjectId) {
                        spinner.setSelection(i, true)
                        initQuestionSetSpinner()
                        break
                    }
                }
            }

            spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onNothingSelected(parent: AdapterView<*>?) {

                }

                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    //切换后更新答案类型
                    subjectId = id.toInt()
                    //刷新该科目的错题集
                    initQuestionSetSpinner()
                }
            }
        })
    }

    /**
     * 初始化题目错题集的下拉选择
     */
    private fun initQuestionSetSpinner() {
        viewModel.getQuestionSet(getLoginUserId(), subjectId).observe(this, Observer {
            val spinnerText: TextView = include_question_set.findViewById(R.id.textView_spinner)
            val spinner: Spinner = include_question_set.findViewById(R.id.spinner)

            spinnerText.text = getString(R.string.question_set)
            spinner.adapter = SpinnerAdapter(
                this,
                R.layout.view_spinner_item,
                R.id.textView_spinner_item,
                it?.toMutableList()?:ArrayList<QuestionSetEntity>().toMutableList(),
                SpinnerAdapter.TYPE_QUESTION_SET
            )

            //如果当前科目没有错题集，则用-1标记
            if(it.isNullOrEmpty()) {
                questionSetId = -1
                Snackbar
                    .make(add_question_root, getString(R.string.no_question_set), Snackbar.LENGTH_LONG)
                    .setAction(R.string.add_question_set) {
                        addQuestionSet()
                    }
                    .show()
            }
            else {
                //设置默认选择的错题集，因为上次或者首次进入，用户可能有希望的选择
                for (i in it.indices) {
                    if (it[i].id == questionSetId) {
                        spinner.setSelection(i, true)
                        break
                    }
                }
            }

            spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onNothingSelected(parent: AdapterView<*>?) {

                }

                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    //切换后更新答案类型
                    questionSetId = id.toInt()
//
//                    //通过错题本获取科目
//                    viewModel.getSubjectById(it!![position].subjectId).observe(this@AddQuestionActivity, Observer {subjectEntity->
//                        subjectId = subjectEntity?.id?:1
//                        textView_subject.text = subjectEntity?.name
//                    })
                }
            }
        })
    }

    /**
     * 修改错题本信息
     */
    private fun addQuestionSet() {
        val builder = MaterialAlertDialogBuilder(this)
        val dialog = builder.create()
        dialog.apply {
            val view = LayoutInflater.from(this@AddQuestionActivity).inflate(R.layout.view_add_question_set, null, false)
            val nameEditText: TextInputEditText = view.findViewById(R.id.edit_add_question_set_name)
            val descriptionEditText: TextInputEditText = view.findViewById(R.id.edit_add_question_set_description)
            val includeSubject: View = view.findViewById(R.id.include_subject)
            val spinnerText: TextView = includeSubject.findViewById(R.id.textView_spinner)
            val spinner: Spinner = includeSubject.findViewById(R.id.spinner)

            //填充spinnerView
            spinnerText.text = "所属科目"
            getLoginUserId(object : OnRefreshListener<String>() {
                override fun onUpdate(obj: String) {
                    super.onUpdate(obj)

                    viewModel.getSubjectByUserId(obj).observe(this@AddQuestionActivity, Observer {
                        spinner.adapter = SpinnerAdapter(
                            this@AddQuestionActivity,
                            R.layout.view_spinner_item,
                            R.id.textView_spinner_item,
                            it?.toMutableList()?:ArrayList<SubjectEntity>().toMutableList(),
                            SpinnerAdapter.TYPE_SUBJECT
                        )

                        //设置默认选择的科目，因为上次或者首次进入，用户可能有希望的选择
                        if (it != null) {
                            for (i in it.indices) {
                                if (it[i].id == subjectId) {
                                    spinner.setSelection(i, true)
                                    break
                                }
                            }
                        }

                        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                            override fun onNothingSelected(parent: AdapterView<*>?) {

                            }

                            override fun onItemSelected(
                                parent: AdapterView<*>?,
                                view: View?,
                                position: Int,
                                id: Long
                            ) {
                                //切换后更新科目类型
                                subjectId = id.toInt()
                            }
                        }
                    })
                }
            })

            setView(view)
            setTitle(getString(R.string.add_question_set))

            setButton(Dialog.BUTTON_POSITIVE, "确定") { _, _ ->
                val name0 = nameEditText.text?.toString()
                val description0 = descriptionEditText.text?.toString()
                if (name0.isNullOrBlank()) {
                    Toasty.error(context, getString(R.string.question_set_error)).show()
                    //Snackbar.make(add_question_root, getString(R.string.question_set_error), Snackbar.LENGTH_SHORT).show()
                } else {
                    viewModel.addQuestionSet(getLoginUserId(), name0, description0, subjectId, "#8AB4F8")
                    Toasty.success(context, getString(R.string.add_question_set_success)).show()
                    //Snackbar.make(add_question_root, getString(R.string.add_question_set_success), Snackbar.LENGTH_SHORT).show()
                }
                dialog.dismiss()
            }
        }
        dialog.show()
    }

    /**
     * 初始化题目类型的下拉选择
     */
    private fun initQuestionTypeSpinner() {
        viewModel.getQuestionType().observe(this, Observer {
            val spinnerText: TextView = include_question_type.findViewById(R.id.textView_spinner)
            val spinner: Spinner = include_question_type.findViewById(R.id.spinner)

            spinnerText.text = getString(R.string.question_type)
            spinner.adapter = SpinnerAdapter(
                this,
                R.layout.view_spinner_item,
                R.id.textView_spinner_item,
                it?.toMutableList()?:ArrayList<QuestionSetEntity>().toMutableList(),
                SpinnerAdapter.TYPE_QUESTION_TYPE
            )

            if (!it.isNullOrEmpty()) {
                //设置默认选择的题目类型，只有编辑题目会用得上
                for (i in it.indices) {
                    if (it[i].id == questionType) {
                        spinner.setSelection(i, true)
                        break
                    }
                }
            }

            spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onNothingSelected(parent: AdapterView<*>?) {

                }

                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    //切换后更新答案类型
                    questionType = id.toInt()
                    updateQuestionTypeView()
                }
            }
        })
    }

    /**
     * 添加标题
     */
    private fun initAddQuestionTitle() {
        imageView_expend.setOnClickListener {
            val titleText = edit_add_title.text?.toString()
            val intent = Intent(this, AddQuestionExpendActivity::class.java)
            intent.putExtra("type", TYPE_TITLE)
            intent.putExtra("text", titleText)
            startActivityForResult(intent, TagUtils.ADD_QUESTION)
        }
    }

    /**
     * 不同的题型答案的类型也不同，选择填空判断往往有正确答案，而大题则没有
     *
     * 现在，均可以添加图片
     */
    private fun updateQuestionTypeView() {
        val answerView = LayoutInflater.from(this).inflate(R.layout.view_question_big_question, null, false)
        answerEditText = answerView.findViewById(R.id.edit_answer)
        val expendView: MaterialButton = answerView.findViewById(R.id.imageView_expend)
        expendView.setOnClickListener {
            val titleText = edit_add_title.text?.toString()
            val intent = Intent(this, AddQuestionExpendActivity::class.java)
            intent.putExtra("type", TYPE_ANSWER)
            intent.putExtra("text", answerEditText?.text?.toString())
            startActivityForResult(intent, TagUtils.ADD_QUESTION)
        }

        linearLayout_answer_root.removeAllViews()
        linearLayout_answer_root.addView(answerView)
//        //大题的答案
//        if (questionType == QUESTION_TYPE_DT) {
//            val answerView = LayoutInflater.from(this).inflate(R.layout.view_question_big_question, null, false)
//            answerEditText = answerView.findViewById(R.id.edit_answer)
//            val expendView: MaterialButton = answerView.findViewById(R.id.imageView_expend)
//            expendView.setOnClickListener {
//                val titleText = edit_add_title.text?.toString()
//                val intent = Intent(this, AddQuestionExpendActivity::class.java)
//                intent.putExtra("type", TYPE_ANSWER)
//                intent.putExtra("text", answerEditText?.text?.toString())
//                startActivityForResult(intent, TagUtils.ADD_QUESTION)
//            }
//
//            linearLayout_answer_root.removeAllViews()
//            linearLayout_answer_root.addView(answerView)
//        }
//        //小题的答案
//        else {
//            val answerView = LayoutInflater.from(this).inflate(R.layout.view_question_small_question, null, false)
//            answerEditText = answerView.findViewById(R.id.edit_answer)
//
//            linearLayout_answer_root.removeAllViews()
//            linearLayout_answer_root.addView(answerView)
//        }
    }

    /**
     * 初始化问题标签
     */
    private fun initQuestionTag() {
        //删除模式
        var deleteModel = false
        imageView_add_tag.setOnClickListener {
            val builder = MaterialAlertDialogBuilder(this)
            builder.apply {
                val view = LayoutInflater.from(this@AddQuestionActivity).inflate(R.layout.view_add_tag, null, false)
                val editText: TextInputEditText = view.findViewById(R.id.edit_add_tag)
                setView(view)
                setTitle(getString(R.string.add_tag))
                setPositiveButton("确定") {_, _ ->
                    val text = editText.text?.toString()
                    if (text.isNullOrBlank()) {
                        Snackbar.make(imageView_add_tag, getString(R.string.question_tag_error), Snackbar.LENGTH_SHORT).show()
                    } else {
                        val chip = Chip(this@AddQuestionActivity)
                        chip.text = text
                        chip.setOnCloseIconClickListener {
                            chip_group.removeView(chip)
                        }
                        //在删除模式添加更改回查看状态
                        if (deleteModel) {
                            changeTagDeleteModel(deleteModel)
                            deleteModel = !deleteModel
                        }
                        chip_group.addView(chip)
                    }
                }
            }
            builder.create().show()
        }

        //删除模式切换
        imageView_delete_model.setOnClickListener {
            changeTagDeleteModel(deleteModel)
            deleteModel = !deleteModel
        }
    }

    /**
     * 更改标签删除状态
     */
    private fun changeTagDeleteModel(deleteModel: Boolean) {
        //删除模式
        if (deleteModel) {
            for (i in 0 until chip_group.childCount) {
                (chip_group[i] as Chip).isCloseIconVisible = false
            }
        } else {
            for (i in 0 until chip_group.childCount) {
                (chip_group[i] as Chip).isCloseIconVisible = true
            }
        }
    }

    private fun toSave(userId: String, tag: String, titleText: String, answerText: String, familiarity: Float, score: Float, difficulty: Float) {
        when (type) {
            TYPE_ADD -> {
                val nowTime = TimeUtils.getNowTime()
                viewModel.toSaveQuestion(
                    userId,
                    questionSetId,
                    subjectId,
                    questionType,
                    tag,
                    titleText,
                    answerText,
                    familiarity,
                    difficulty,
                    nowTime,
                    0,
                    null,
                    nowTime,
                    score,
                    nowTime
                )
                viewModel.toSaveQuestionInfo(this, familiarity)
            }
            TYPE_EDIT -> {
                if (editQuestionEntity != null) {
                    viewModel.updateQuestion(
                        QuestionEntity(
                            editQuestionEntity!!.id,
                            editQuestionEntity!!.userId,
                            questionSetId,
                            subjectId,
                            questionType,
                            tag,
                            titleText,
                            answerText,
                            editQuestionEntity!!.familiarity,
                            difficulty,
                            editQuestionEntity!!.insertTime,
                            editQuestionEntity!!.doCount,
                            editQuestionEntity!!.note,
                            editQuestionEntity!!.lastTime,
                            score
                        )
                    )
                }
            }
        }

        Toasty.success(this, getString(R.string.save_success), Toasty.LENGTH_SHORT).show()
        finish()
    }

    /**
     * 初始化编辑的内容
     */
    private fun initEditContent() {
        if (editQuestionEntity != null) {
            //设置默认的选项
            subjectId = editQuestionEntity!!.subjectId
            questionSetId = editQuestionEntity!!.questionSetId
            questionType = editQuestionEntity!!.typeId

            //刷新答案布局，否则下方答案添加不进去
            updateQuestionTypeView()

            //设置标题等信息
            edit_add_title.setText(editQuestionEntity!!.titlePath)
            answerEditText?.setText(editQuestionEntity!!.answerPath)
            edit_score.setText(editQuestionEntity!!.score.toString())

            //添加标签
            if (!editQuestionEntity!!.tag.isBlank()) {
                editQuestionEntity!!.tag.split("#").forEach {
                    val chip = Chip(this)
                    chip.text = it
                    chip_group.addView(chip)
                }
            }

            //添加难度
            ratingBar.rating = editQuestionEntity!!.difficulty
        }
    }

//    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
//        menuInflater.inflate(R.menu.menu_add_question, menu)
//        return super.onCreateOptionsMenu(menu)
//    }
//
//    override fun onOptionsItemSelected(item: MenuItem): Boolean {
//        when (item.itemId) {
//            R.id.to_save -> {
//
//            }
//        }
//        return super.onOptionsItemSelected(item)
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == TagUtils.ADD_QUESTION) {
            when (resultCode) {
                TYPE_TITLE -> edit_add_title.setText(data?.getStringExtra("text"))
                TYPE_ANSWER -> answerEditText?.setText(data?.getStringExtra("text"))
            }
        }
    }

    /**
     * 返回键二次确认
     */
    private fun backWarning() {
        val builder = MaterialAlertDialogBuilder(this)
        builder.apply {
            setTitle(getString(R.string.warning_title))
            setMessage(Html.fromHtml(getString(R.string.back_warning_add_question)))
            setNegativeButton("返回") {_, _ ->
                finish()
            }
            setPositiveButton("继续编辑") {_, _ ->}

        }
        builder.create().show()
    }

    override fun onBackPressed() {
        backWarning()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                backWarning()
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    companion object {
        const val TYPE_TITLE = 1
        const val TYPE_ANSWER = 2

        //选择
        const val QUESTION_TYPE_XZ = 1
        const val QUESTION_TYPE_TK = 2
        const val QUESTION_TYPE_PD = 3
        const val QUESTION_TYPE_DT = 4

        //当前受理的是添加还是编辑模式
        const val TYPE_ADD = 1
        const val TYPE_EDIT = 2

        //又采用了这种不大好的方式，但是方便啊
        var editQuestionEntity: QuestionEntity? = null
    }
}